﻿using BaseUtils.Helper;
using BaseUtils.Logger;
using DatabaseCore.Sqlite;
using DeviceManage.PLC;
using NW_WEB_Service.App.Interface;
using NW_WEB_Service.com.app.entities.modal;
using NW_WEB_Service.com.app.Interface;
using NW_WEB_Service.com.app.services;
using Service.src.com.app.entities.modal;
using Service.src.com.utils.modal;
using Service.src.Flow.Server;
using Service.src.NW.Enum;
using Service.src.NW.Model;
using Service.src.NW.Model.Drive;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Net;
using System.Web.Http;
using System.Threading.Tasks;

namespace NW_WEB_Service.com.app.controllers
{
    [RoutePrefix("api/device")]
    public class DeviceController : ApiController
    {
        public DeviceInterface DeviceServer;
        private PlcInterface PlcService;
        public SysDriverAdressInterface SysDriverAdressServer;

        [Obsolete("暂时弃用，后期移植到 DeviceServer")]
        public static SysDriverServer driverServer;


        public DeviceController()
        {
            DeviceServer = new DeviceService();
            PlcService = new PlcService();
            SysDriverAdressServer = new SysDriverAdressService();
            driverServer = new SysDriverServer();
        }

        /// <summary>
        /// 根据 ID 获取设备详情数据
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("{id:int}")]
        public HttpResult GetDriver(int Id)
        {
            SysDevicrInfo Res = DeviceServer.GetDeviceById(Id);
            return new HttpResult().Success(Res);
        }

        /// <summary>
        /// 添加设备，更新设备
        /// </summary>
        /// <param name="DriveJson"></param>
        /// <returns></returns>
        [HttpPost]
        [Route]
        public HttpResult AddDrive([FromBody] SysDevicrInfo plcDriveInfo)
        {
            if (plcDriveInfo?.Id > 0)
            {
                DeviceServer.UpldateDrive(plcDriveInfo);
            }
            else
            {
                plcDriveInfo = DeviceServer.AddDrive(plcDriveInfo);
            }

            if (plcDriveInfo.Id > 0)
            {
                Task.Run(() =>
                {
                    new AppData().StartDevice(plcDriveInfo);
                });
            }
            return new HttpResult().Success(plcDriveInfo);
        }

        /// <summary>
        /// 根据 ID 删除设备
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete]
        [Route("{id:int}")]
        public HttpResult DeleteDriver(int Id)
        {
            bool Res = DeviceServer.DeleteDriver(Id);
            if (Res)
            {
                SysDriverAdressServer.DeleteAddressByDriverId(Id);
            }
            return new HttpResult().Success(Res);
        }

        /// <summary>
        /// 获取所有设备
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("list")]
        public HttpResult GetDrivelist()
        {
            List<SysDevicrInfo> Devices = DeviceServer.GetList();
            if (Devices == null || Devices.Count <= 0)
            {
                Devices = new List<SysDevicrInfo>();
            }
            SysDevicrInfo Info = new SysDevicrInfo();
            Info.DeviceName = "全局变量";
            Info.DeviceType = DeviceTypeEnum.GLOBAL_PARAM.ToString();
            Info.Id = -99;
            Devices.Add(Info);

            return new HttpResult().Success(Devices);
        }


        /// <summary>
        /// 获取PLC地址
        /// </summary>
        /// <param name="DriverType"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("plc/address/{DriverType}")]
        public HttpResult QueryByDriverType(string DriverType)
        {
            List<SysPlcDriverAddress> Address = PlcService.QueryByDriverType(DriverType);
            if (Address == null || Address.Count <= 0)
            {
                Address = new List<SysPlcDriverAddress>();
            }
            return new HttpResult().Success(Address);
        }

        /// <summary>
        /// 获取对应plc的Address
        /// </summary>
        /// <param name="DriverId">设备id</param>
        /// <returns></returns>
        [HttpGet]
        [Route("plc/address-by/{DriverId:int}")]
        public HttpResult GetPlcAddressByDriverId(int DriverId)
        {
            HttpResult Result = new HttpResult();
            if (DriverId <= 0)
            {
                Result.Data = new List<SysPlcDriverAddress>();
            }
            else
            {
                List<SysPlcDriverAddress> Address = DeviceServer.GetAddresslist(DriverId);
                Result.Data = Address;
            }

            return Result;
        }
        /// <summary>
        /// 添加Address，更新Address
        /// </summary>
        /// <param name="DriveJson"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("plc/address/save")]
        public HttpResult UpdateAddress([FromBody] SysPlcDriverAddressDTO AddressDTO)
        {
            SysPlcDriverAddress Address = new SysPlcDriverAddress();
            Address.Address = AddressDTO.Address;
            Address.Desc = AddressDTO.Desc;
            Address.DriverId = AddressDTO.DriverId;
            Address.Name = AddressDTO.Name;

            Address.DriverType = DeviceTypeEnum.PLC;
            if (AddressDTO?.Id > 0)
            {
                Address.Id = AddressDTO.Id;
                SysDriverAdressServer.UpldateAddress(Address);
            }
            else
            {
                Address = SysDriverAdressServer.AddAddress(Address);
            }
            return new HttpResult().Success(Address);
        }

        /// <summary>
        /// 根据 ID 删除Address
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete]
        [Route("plc/address/{Id:int}")]
        public HttpResult Delete(int Id)
        {
            bool res = SysDriverAdressServer.DeleteAddress(Id);
            return new HttpResult().Success(res);
        }

        [HttpGet]
        [Route("plc/synchronization-data/{DeviceType}/{DriverId:int}")]
        public HttpResult Get(string DeviceType, int DriverId)
        {
            List<SysPlcDriverAddress> Address = DeviceServer.GetAddresslist(DriverId);
            IPLCHelper Helper = AppData.IPLCHelpers[DriverId];
            foreach (SysPlcDriverAddress Offset in Address)
            {
                if (!Helper.LinkSucceed)
                {
                    Offset.Value1 = "同步失败，原因：PLC未连接成功";
                    continue;
                }
                try
                {
                    var Val = Helper.Read(Offset.Address);
                    Offset.Value1 = Val.ToString();
                }
                catch (Exception ex)
                {
                    Offset.Value1 = $"同步失败，原因：{ex.Message}";
                    LoggerService.Error(Offset.Value1, ex);
                }
            }
            return new HttpResult().Success(Address);
        }

        [HttpPost]
        [Route("socket/send-message")]
        public HttpResult SendMessage([FromBody] SocketMessageDTO SocketMessage)
        {
            EventServer Event = new EventServer();
            bool Res = Event.SendMessage(SocketMessage.ServerId, SocketMessage.ClientIndex, SocketMessage.Message);
            return new HttpResult().Success(Res);
        }

        [HttpGet]
        [Route("socket/clients/{ServerId}")]
        public HttpResult GetConnectedClients(int ServerId)
        {
            EventServer Event = new EventServer();
            List<TcpClient> Clients = Event.GetConnectedClients(ServerId);
            List<string> ips = new List<string>();
            foreach (TcpClient item in Clients)
            {
                ips.Add(((IPEndPoint)item.Client.RemoteEndPoint).Address.ToString());
            }

            return new HttpResult().Success(ips);
        }

    }
}
